import React from 'react';
import { Menu, Dropdown, Tag } from 'antd';
import style from '../Layout.module.less';
import { routeItem } from '@/router';
import { useHistory } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { changeTabList, replaceActiveKey } from '@/store/counterSlice';
import { useTranslation } from 'react-i18next';

const BaseNav = () => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const history = useHistory();
  const { tabList, activeKey } = useSelector((state: any) => ({
    tabList: state.counter.tabList,
    activeKey: state.counter.activeKey,
  }));

  const onClick = ({ key }: any, item: routeItem) => {
    console.log(key);
    console.log(item);
    switch (key) {
      case '1':
        history.go(0);
        break;
      case '2':
        if (item.path == '/') {
          dispatch(changeTabList({ tabList: [{ title: '首页', path: '/', name: 'home' }] }));
          localStorage.setItem(
            'tabList',
            JSON.stringify([{ title: '首页', path: '/', name: 'home' }]),
          );
        } else {
          dispatch(changeTabList({ tabList: [{ title: '首页', path: '/' }, { ...item }] }));
          localStorage.setItem(
            'tabList',
            JSON.stringify([{ title: '首页', path: '/', name: 'home' }, { ...item }]),
          );
        }
        break;
      default:
        dispatch(changeTabList({ tabList: [{ title: '首页', path: '/', name: 'home' }] }));
        localStorage.setItem(
          'tabList',
          JSON.stringify([{ title: '首页', path: '/', name: 'home' }]),
        );
        history.push('/');
        // setPathname('/')
        dispatch(replaceActiveKey({ activeKey: '/' }));
    }
  };
  const renderMenu = (item: routeItem) => (
    <Menu
      onClick={(e) => {
        onClick(e, item);
      }}
    >
      <Menu.Item key="1">刷新</Menu.Item>
      <Menu.Item key="2">关闭其他</Menu.Item>
      <Menu.Item key="3">关闭所有</Menu.Item>
    </Menu>
  );
  return (
    <div className={style.nav}>
      {tabList.map((item: routeItem) => {
        return (
          <Dropdown overlay={() => renderMenu(item)} trigger={['contextMenu']} key={item.path}>
            <Tag
              style={{ padding: '5px 10px', cursor: 'pointer' }}
              onClick={() => {
                history.push(item.path);
                dispatch(replaceActiveKey({ activeKey: item.path }));
              }}
              className={activeKey === item.path ? `${style.active}` : ''}
            >
              {t(item.name as string)}
            </Tag>
          </Dropdown>
        );
      })}
    </div>
  );
};

export default BaseNav;
